/**
 * 跑马灯
 * 注：仅播放一次，如需循环播放，请使用onEnd参数来实现
 * 
 * @author steven0lisa@live.com
 * @since 2018-03-21
 * 
 * Example:
 * 
    var text = '走马灯';
    $.marquee.init({
        el: '#marquee', //指定渲染元素
        speed: 1, //播放速度
        onEnd: function(){ //当播放完成后，回调
            $.marquee.setText(text);
        }
    });

    $.marquee.setText(text);
 * 
 */
(function($){
    var option = {};
    var $ctn;
    var $textWrapCtn;
    var $textCtn;
    var onEnd;
    var EmptyFn = function(){};

    var animateInterval;
    var speed = 1;
    var left = 0;
    var textWidth = 0;

    /**
     * 初始化DOM
     */
    var initUI = function(){
        var html = '<div class="icon-notice"></div>'
        +'<div class="text-wrap">'
        +'    <div class="text"></div>'
        +'</div>';
        $ctn.addClass('marquee');
        $ctn.html(html);
    }

    /**
     * 开始跑马灯动画
     */
    var startMarquee = function(){
        //取消动画
        clearInterval(animateInterval);

        textWidth = $textCtn.width();
        textWrapWidth = $textWrapCtn.width();

        //重置动画
        left = 0 - (textWidth > textWrapWidth ? textWidth : textWrapWidth);
        $textCtn.css({
            left: '0px'
        });


        //开始动画
        animateInterval = setInterval(function(){
            if(left >= textWidth){
                clearInterval(animateInterval);
                onEnd();
                return;
            }
            //步增动画
            left += speed;
            $textCtn.css({
                left: (0-left) + 'px'
            });

        }, 10);
    }

    //定义跑马灯
    $.marquee = {
        //初始化
        init: function(option){
            //处理参数
            $ctn = $(option.el);
            onEnd = option.onEnd || EmptyFn;
            speed = option.speed || 1;
            //初始化UI
            initUI();
            $textWrapCtn = $ctn.find('.text-wrap');
            $textCtn = $ctn.find('.text');
        },
        //设置文本
        setText: function(text){
            $textCtn.html(text);
            setTimeout(startMarquee, 10);
        },
        //取消跑马灯
        destory: function(){
            if($ctn){
                clearInterval(animateInterval);
                $ctn.html('');
                $ctn.removeClass('marquee');
            }
        }
    }
})(jQuery);